package cn.k23.bymain.controller.common;

import cn.k23.bymain.bean.common.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description:全局异常处理
 * @Author: k23
 * @Date: 2022-05-11 11:23
 * @Version: 1.0
 */

@RestControllerAdvice  //全局接口异常处理的类，当发生异常没有捕获时，便会触发这个异常
@Slf4j
public class GlobalExceptionController extends BaseController{
    //捕获校验参数异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBean handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error(e.toString());
        BindingResult result=e.getBindingResult();
        Map map=new HashMap();
        //获取出错的字段 参数名
        List<FieldError> list= result.getFieldErrors();
        Iterator<FieldError> it=list.iterator();
        while(it.hasNext()){
            FieldError error=it.next();
            map.put(error.getField(),error.getDefaultMessage());
        }
        return fail("验证失败",map);
    }

}
